<template>
    <div class="btn" @click="releaseNotice">发布公告</div>
    <div>
        <el-dialog v-model="dialogVisible" title="公告信息" width="30%" top="10vh" :open-delay=500 :before-close="handleClose">
            <div class="container">
                <p class="area-phone">发布公告的区域和物业电话</p>
                <div class="main">
                    <el-input v-model="searchArea" placeholder="请输入需要查询的小区" @keyup.enter="search">
                        <template #append>
                            <div class="icon" @click="refreshArea">
                                <el-icon>
                                    <Refresh />
                                </el-icon>
                            </div>
                        </template>
                    </el-input>
                    <el-table :data="areaInfo.slice((currentPage - 1) * pageSize, currentPage * pageSize)" stripe
                        style="width: 100%" border>
                        <el-table-column prop="name" label="区域名称" align="center" />
                        <el-table-column prop="phone" label="物业电话" align="center" />
                    </el-table>
                    <el-pagination background layout="prev, pager, next" :total=areaInfo.length :page-size="pageSize"
                        :current-page="currentPage" @current-change="handleCurrentChange"></el-pagination>
                </div>
                <div class="notice-content">
                    <span>公告信息:</span>
                    <el-input v-model="noticeContent" :rows="2" type="textarea" placeholder="请输入公告内容" />
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="sendingNotice">发送</el-button>
                    <el-button @click="cancel">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { createDraw } from '../../../utils/createDraw'
import * as turf from '@turf/turf'
import { Query } from '../../../utils/Query'
import { sendingNoticeHttp } from '../../../request/api'
import { Refresh } from '@element-plus/icons-vue'

const $map = ref(null)
const source = ref(null)
//居民区
const residential = {
    type: "FeatureCollection",
    features: []
}
//模态框是否显示
const dialogVisible = ref(false)
//受影响的居民区
const areaInfo = ref([])
//分页器的设置
const pageSize = ref(5)
const currentPage = ref(1)
const handleCurrentChange = (curPage) => {
    currentPage.value = curPage
}
//查询居民区
const searchArea = ref('')
const tempClone = ref([])
const search = () => {
    if (tempClone.value.length === 0) {
        tempClone.value = areaInfo.value
    }
    areaInfo.value = tempClone.value.filter(item => item.name.includes(searchArea.value))
}
const refreshArea = () => {
    if (tempClone.value.length === 0) {
        searchArea.value = ''
        return
    }
    areaInfo.value = tempClone.value
    searchArea.value = ''
    tempClone.value = []
}

const noticeContent = ref('')

onMounted(() => {
    $map.value = inject("$map")
    const style = new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: "#fff",
            width: 3,
        }),
        fill: new ol.style.Fill({
            color: "#333"
        })
    })
    source.value = new ol.source.Vector({})
    const layer = new ol.layer.Vector({
        source: source.value,
        style
    })
    $map.value.addLayer(layer)

    Query.queryByLayerId({
        service: {
            name: "guanggu",
            layerId: 0
        },
        callback: handleQuery
    })
})
//获取所有的居民区数据
const handleQuery = (data) => {
    data.SFEleArray.map(item => {
        const properties = {
            id: item.FID,
            name: item.AttValue[3],
            phone: item.AttValue[4]
        }
        const position = item.fGeom.RegGeom[0].Rings[0].Arcs[0].Dots
        const coordinates = position.map(item => {
            return Object.values(item)
        })
        const feature = {
            type: "Feature",
            geometry: {
                type: "Polygon",
                coordinates: [coordinates],
                properties
            }
        }
        residential.features.push(feature)
    })
}

//用于存储地图双击事件
const dblClickInteraction = ref(null)

//点击发布公告
const releaseNotice = () => {
    if(dblClickInteraction.value!==null){
        return
    }
    //禁用地图双击事件
    //获取地图双击事件
    dblClickInteraction.value = $map.value
        .getInteractions()
        .getArray()
        .find(interaction => {
            return interaction instanceof ol.interaction.DoubleClickZoom;
        });
    //移除地图双击事件
    $map.value.removeInteraction(dblClickInteraction.value);

    //添加画笔
    const draw = createDraw({
        type: "LineString",
        source: source.value
    })
    $map.value.addInteraction(draw)
    draw.on("drawend", handleDraw)
}

const handleDraw = (evt) => {
    const position = evt.feature.getGeometry().getCoordinates()
    const line = turf.lineString(position)
    //创建缓冲区
    const lineBuffer = turf.buffer(line, 0.2, { units: 'kilometers' });

    const features = new ol.format.GeoJSON().readFeatures({
        type: "FeatureCollection",
        features: [line, lineBuffer]
    })
    source.value.addFeatures(features)

    const joinResidential = ref([])
    residential.features.map(item => {
        //缓冲区与居民区是否不相交
        const isJoin = turf.booleanDisjoint(lineBuffer, item);
        if (!isJoin) {
            joinResidential.value.push(item)
            areaInfo.value.push({
                name: item.geometry.properties.name,
                phone: item.geometry.properties.phone
            })
        }
    })

    //移除画笔
    $map.value.getInteractions().pop()
    //恢复地图双击事件
    setTimeout(() => {
        $map.value.addInteraction(dblClickInteraction.value)
    }, 10)
    dialogVisible.value = true
}

//发送
const sendingNotice = () => {
    if (noticeContent.value.trim() === "") {
        ElMessage({
            message: '公告内容为空',
            type: 'warning',
            duration: 1000
        })
        return
    }
    const time = getNowDate()
    //接口参数
    const info = {
        username: localStorage.getItem("username"),
        content: noticeContent.value.trim(),
        time
    }
    sendingNoticeHttp(info).then(res => {
        console.log(res);
        dialogVisible.value = false
        source.value.clear()
        ElMessage({
            message: '发送成功',
            type: 'success',
            duration: 1000
        })
    })
    searchArea.value = ''
    noticeContent.value = ''
    tempClone.value = []
}

//取消发送
const cancel = () => {
    dialogVisible.value = false
    source.value.clear()
    areaInfo.value = []
    searchArea.value = ''
    noticeContent.value = ''
    tempClone.value = []
    dblClickInteraction.value = null
}
const handleClose = () => {
    cancel()
}

function getNowDate() {
    var myDate = new Date;
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日
    var hours = myDate.getHours(); //获取当前小时
    var minutes = myDate.getMinutes(); //获取当前分钟
    var seconds = myDate.getSeconds(); //获取当前秒
    var now = year + "/" + mon + "/" + date + " " + hours + ":" + minutes + ":" + seconds;
    return now;
}


</script>

<style lang="scss" scoped>
.btn {
    cursor: pointer;
}

.container {
    border: 1px solid #d1d1d1;

    .area-phone {
        display: inline-block;
        height: 30px;
        width: 100%;
        background-color: #eaeaea;
        padding-left: 10px;
        line-height: 30px;
        color: #3f3f3f;
    }

    .main {
        padding: 10px;
        border: 1px solid #d1d1d1;
        display: flex;
        flex-direction: column;
        gap: 10px;

        :deep(.el-input-group__append) {
            cursor: pointer;
            padding: 0;

            .icon {
                width: 100%;
                height: 100%;
                background-color: #e8e8e8;
                padding: 0 20px;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            &:hover {
                .el-icon {
                    transform: rotate(180deg);
                    transition: all 1s;
                }
            }

            .el-icon {
                color: #3f3f3f;
                font-size: 16px;
            }
        }

        :deep(.cell) {
            color: #3f3f3f;
        }

        .el-pagination {
            margin-bottom: 10px;
            margin-left: auto;

            :deep(.btn-prev) {
                width: 15px;
                height: 27px;
            }

            :deep(.number) {
                width: 15px;
                height: 27px;
            }

            :deep(.btn-next) {
                width: 15px;
                height: 27px;
            }
        }
    }

    .notice-content {
        display: flex;
        gap: 20px;
        padding: 10px;

        span {
            font-weight: 900;
        }

        .el-textarea {
            width: 80%;
        }

    }
}

:deep(.el-dialog__header) {
    padding: 20px 20px;
    border-bottom: 1px solid #c7c7c7;
    margin-right: 0;
}
</style>